package com.xf.zk.curator.example.elections;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.leader.LeaderLatch;
import org.apache.curator.framework.recipes.leader.LeaderLatchListener;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.curator.retry.ExponentialBackoffRetry;

import java.io.IOException;

public class LeaderLatchTest {
    static String leader_path = "/curator_recipes_latch_path";

    public static void main(String[] args) throws Exception {
        // 模拟3个线程分别获取1个客户端连接进行master选举
        Runnable target = new Runnable() {
            @Override
            public void run() {
                CuratorFramework client = newClient();
                client.start();
                // LeaderLatch,路径为/curator_recipes_leader_path，并注册
                final LeaderLatch latch = new LeaderLatch(client,leader_path,Thread.currentThread().getId()+"");
                latch.addListener(new LeaderLatchListener() {
                    @Override
                    public void isLeader() {
                        System.out.println(Thread.currentThread().getName() + "成为Master角色");
                        // 此处执行选举成功后的业务逻辑
                        try {
                            Thread.sleep(3000);
                            // 调用close方法释放资源
                            latch.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        System.out.println(Thread.currentThread().getName() + "完成Master操作，释放Master权利");
                    }

                    @Override
                    public void notLeader() {
                        System.out.println(Thread.currentThread().getName() + "没有成为Master角色");
                    }
                });
                try {
                    latch.start();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        };
		Thread thread1 = new Thread(target);
		Thread thread2 = new Thread(target);
		Thread thread3 = new Thread(target);
		thread1.start();
		thread2.start();
		thread3.start();
        Thread.sleep(Integer.MAX_VALUE);
    }

    public static CuratorFramework newClient() {
        return CuratorFrameworkFactory.builder().connectString("127.0.0.1:2181,127.0.0.1:2182,127.0.0.1:2183")
				.retryPolicy(new ExponentialBackoffRetry(1000, 3)).build();
    }

}
